package xiaocao.remove.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class RemoveSvnFile {
	
	private File file;
	
	private String perfix;
	
	public RemoveSvnFile(File file, String perfix) {
		this.file = file;
		this.perfix = perfix;
	}
	
	public static void main(String args[]) throws Exception {
		BufferedReader br=new  BufferedReader(new InputStreamReader(System.in)); 
		BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); 
		bw.write("请输入文件路径："); 
		bw.flush();
		String filePath = br.readLine(); 
		bw.write("请输入文件后缀："); 
		bw.flush();
		String prefix = br.readLine();
		RemoveSvnFile remove = new RemoveSvnFile(new File(filePath), prefix);
		remove.clear();
	}
	
	
	public void clear() {
		clearFile(file);
		file.deleteOnExit();
	}
	
	/**
	 * 清除指定目录下的指定后缀的目录文件
	 * @param file 指定目录
	 */
	private void clearFile(File file) {
		if(file == null || file.listFiles() == null) return;
		for(File f : file.listFiles()) {
			if(perfix == null || perfix.equals("")) {
				deleteDirectoryOrFile(f);
			}
			else if(f.getName().endsWith(perfix)) {
				deleteDirectoryOrFile(f);
			} else {
				clearFile(f);
			}
		}
	}
	
	private void deleteDirectoryOrFile(File file) {
		if(file == null) return;
		if(file.listFiles() == null) {
			// 取得父文件
			File parent = file.getParentFile();
			// 删除当前文件
			file.delete();
			// 删除它所有的父文件
			while(parent != null && (parent.listFiles() == null || parent.listFiles().length == 0)) {
				parent.delete();
				parent = parent.getParentFile();
				if(parent != null && parent.getAbsolutePath().equals(file.getAbsoluteFile())) {
					break;
				}
			}
			return;
		}
		for(File f : file.listFiles()) {
			deleteDirectoryOrFile(f);
		}
	}
}
